//
//  AppDelegate.m
//  FactorySale
//
//  Created by 李 on 2020/1/1.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarViewController.h"
#import "LoginViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AdSupport/AdSupport.h>//idfa功能头文件(可选)
#import <UserNotifications/UserNotifications.h>
#import "JPUSHService.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
/*
厂商端 极光推送
AppKey：70c2b8cb2b8261da911bcae4
Master Secret：917600e815552b0af76cf33c
*/
static NSString *APIKey = @"";
static NSString *const jpushAppKey = @"70c2b8cb2b8261da911bcae4";
static NSString *const channel = @"";
static BOOL isProduction = false;

@interface AppDelegate ()<JPUSHRegisterDelegate,JPUSHGeofenceDelegate,AVAudioPlayerDelegate,UNUserNotificationCenterDelegate,WXApiDelegate>
@property (nonatomic, retain) AVAudioPlayer *player;
@property (nonatomic,strong)UIView *alertBgView;
@property (nonatomic, strong) UIView *backGroundView;// 提示更新的弹框
@property (nonatomic, strong) NSString * contentStr;
@end

@implementation AppDelegate

#pragma mark - 应用程序启动后，要执行的委托调用，系统启动代理(第一个页面的加载)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    //极光推送
    [self jPushConfigWithOptions:launchOptions];
    //主界面创建
    [self setupRootWindow];
    
    [self appNotActivityWith:launchOptions];
    // 暂时还没接支付 wxc0faecc37e5f61a2这个参数也还是管理端的参数，需要替换
   // [WXApi registerApp:@"wxc0faecc37e5f61a2"];
    
    [self requestVersionNumber];
    
    return YES;
}
- (void)requestVersionNumber{
 
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"type"] = @"6"; //type 4 ios师傅端 5 ios管理端 6 ios厂家端
    [NetWorkTool POST:getIosVersion param:param success:^(id dic) {
        KMyLog(@"返回的数据是 %@",dic);
        NSDictionary *dataDic = dic[@"data"];
        NSString *statusStr = dataDic[@"status"];
        // 从服务器拿到的版本号
        NSString *version = dataDic[@"version"];
        self.contentStr = dataDic[@"content"];
        // 获取当前的版本号
        NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        if ([statusStr isEqualToString:@"0"]) {// 不需要强更

            if (self.backGroundView) {
                [self.backGroundView removeFromSuperview];
            }
        } else {// 需要强制更新
            if ([version isEqualToString:currentVersion]) {// 没有更新
                if (self.backGroundView) {
                    [self.backGroundView removeFromSuperview];
                }
            } else {// 有新版本
                [self updateView];
            }
        }
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
  
}
- (void)updateView{
    if (self.backGroundView) {
        [self.backGroundView removeFromSuperview];
    }
    self.backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
    self.backGroundView.backgroundColor = [UIColor colorWithWhite:0.05 alpha:0.1];
    [[UIApplication sharedApplication].keyWindow addSubview: self.backGroundView];
    

    UIImageView *mainImageView;
    if (mainImageView) {
        [mainImageView removeFromSuperview];
    }
    mainImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"版本更新"]];
    mainImageView.userInteractionEnabled = YES;
    [self.backGroundView addSubview:mainImageView];
    [mainImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(50);
        make.right.offset(-50);
        make.centerX.equalTo(self.backGroundView.mas_centerX);
        make.centerY.equalTo(self.backGroundView.mas_centerY);
        make.height.offset(350);
    }];
    
    UILabel *titleLabel;
    if (titleLabel) {
        [titleLabel removeFromSuperview];
    }
    titleLabel = [[UILabel alloc] init];
    titleLabel.textColor = [UIColor colorWithHexString:@"#343434"];
    titleLabel.text = @"更新内容：";
    titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [mainImageView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(150);
        make.left.offset(30);
        make.right.offset(-30);
        make.height.offset(20);
    }];
    
    UITextView *contentTextView;
    if (contentTextView) {
        [contentTextView removeFromSuperview];
    }
    contentTextView = [[UITextView alloc] init];
    contentTextView.textColor = [UIColor colorWithHexString:@"#343434"];
    contentTextView.font = [UIFont systemFontOfSize:14];
    contentTextView.text = self.contentStr;
    [contentTextView setEditable:NO];
    [self.backGroundView addSubview:contentTextView];
    [contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(0);
        make.left.equalTo(titleLabel.mas_left).offset(0);
        make.right.equalTo(mainImageView.mas_right).offset(-20);
        make.height.offset(120);
    }];
    UIButton *confirmButton;
    if (confirmButton) {
        [confirmButton removeFromSuperview];
    }
    confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmButton setTitle:@"立即更新" forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmUpdateButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton setBackgroundImage:[UIImage imageNamed:@"按钮背景"] forState:UIControlStateNormal];
    confirmButton.layer.cornerRadius = 20;
    confirmButton.layer.masksToBounds = YES;
    [mainImageView addSubview:confirmButton];
    [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(80);
        make.right.offset(-80);
        make.bottom.offset(-10);
        make.height.offset(40);
    }];
}
- (void)confirmUpdateButtonClick:(UIButton *)sender{
    NSString *url = @"https://apps.apple.com/cn/app/%E5%80%99%E4%BF%9D%E5%8E%82%E5%AE%B6%E7%AB%AF/id1495166324";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
#pragma mark - 打开别的APP(支付分享等)
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options {
    
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            //code：拿到授权信息，完成业务逻辑
            KMyLog(@"resultDic%@",resultDic);
            if ([[resultDic objectForKey:@"resultStatus"] integerValue] == 9000) {
                [Center postNotificationName:@"shouquanSuccess" object:nil userInfo:resultDic];
            }
        }];
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            NSString *statues = resultDic[@"resultStatus"];
            if ([statues isEqualToString:@"9000"]) {
                //支付成功后通知后台
                [Center postNotificationName:@"PaySuccess" object:nil];
                
            }else {
                [Center postNotificationName:@"PayFail" object:nil];
            }
        }];
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
    
}
#pragma mark - 微信授权登录 微信支付
-(void)onResp:(BaseResp*)resp{
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        // strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。
        SendAuthResp *aresp = (SendAuthResp *)resp;
        NSDictionary *diccc = @{@"code":aresp.code};
        [Center postNotificationName:@"wechatshouquanSuccess" object:nil userInfo:diccc];
    }
    
    if ([resp isKindOfClass:[PayResp class]]) {
        
        switch (resp.errCode) {
            case WXSuccess: {
                NSLog(@"支付结果: 成功!");
                [Center postNotificationName:@"PaySuccess" object:nil];
            }
                break;
            case WXErrCodeCommon: {
                //签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                NSLog(@"支付结果: 失败!");
            }
                break;
            case WXErrCodeUserCancel: {
                //用户点击取消并返回
                NSLog(@"用户点击取消并返回");
                [Center postNotificationName:@"PayFail" object:nil];
            }
                break;
            case WXErrCodeSentFail: {
                //发送失败
                NSLog(@"发送失败");
            }
                break;
            case WXErrCodeUnsupport: {
                //微信不支持
                NSLog(@"微信不支持");
            }
                break;
            case WXErrCodeAuthDeny: {
                //授权失败
                NSLog(@"授权失败");
            }
                break;
            default:
                break;
        }
    }
}
#pragma mark - 应用程序将要由活动状态切换到非活动状态时执行的委托调用，如按下home 按钮，返回主屏幕，或全屏之间切换应用程序等
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
#pragma mark - 在应用程序已进入后台程序时，要执行的委托调用。所以要设置后台继续运行，则在这个函数里面设置即可
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    //APP角标设置为0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
#pragma mark - 在应用程序要完全退出的时候，要执行的委托调用
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - 在应用程序将要进入前台时(被激活)，要执行的委托调用，与applicationWillResignActive方法相对应
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    //[application cancelAllLocalNotifications];
    [self requestVersionNumber];
    [self.alertBgView removeFromSuperview];
}
#pragma mark - 在应用程序已被激活后，要执行的委托调用，刚好与  applicationDidEnterBackground 方法相对应
- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}
#pragma mark - ******创建主界面******
- (void)setupRootWindow{
//    if (KTOKEN == nil || [KTOKEN isEqualToString:@""]) {
//        //登录界面
//        LoginViewController *vc = [[LoginViewController alloc]init];
//        BaseNavViewController *nav = [[BaseNavViewController alloc]initWithRootViewController:vc];
//        nav.modalPresentationStyle = UIModalPresentationFullScreen;
//        self.window.rootViewController = nav;
//    }  else {
        //创建Tabbar
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        self.window.backgroundColor = [UIColor whiteColor];
        
        TabBarViewController *tabbar = [[TabBarViewController alloc]init];
        self.window.rootViewController = tabbar;
        [self.window makeKeyAndVisible];
//    }
    
    //存储udid
    NSString *udid =[USER_DEFAULT objectForKey:@"udid"];
    if (strIsEmpty(udid)) {
        udid =    [self uuid];
        [USER_DEFAULT setObject:udid forKey:@"udid"];
    }
}
#pragma mark - iOS设备收到一条APNs的处理
//App状态为未运行
- (void)appNotActivityWith:(NSDictionary *)launchOptions{
    //APNs内容获取(APP未运行)
    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    KMyLog(@"APP未运行收到的通知内容%@",remoteNotification);
    if (remoteNotification) {
        KMyLog(@"用户点击APNs通知导致APP被启动");
    }else{
        KMyLog(@"用户其他行为启动APP");
    }
}
#pragma mark - 注册远程推送
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    //上传devieceToken到极光
    [JPUSHService registerDeviceToken:deviceToken];
    KMyLog(@"登录的user_id:%@",KUID);
    //JPush 监听登陆成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidLogin:) name:kJPFNetworkDidLoginNotification object:nil];
}


#pragma mark - 注册远程推送失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"注册远程推送失败: %@", error);
}

//极光推送登录成功后调用的方法
- (void)networkDidLogin:(NSNotification *)notification {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kJPFNetworkDidLoginNotification
                                                  object:nil];
    NSString *str  = [NSString stringWithFormat:@"%@",[JPUSHService registrationID]];
    KMyLog(@"JPush标识此设备的 registrationID:%@",str);
}

#pragma mark - ******极光推送******
- (void)jPushConfigWithOptions:(NSDictionary *)launchOptions{
    // 3.0.0及以后版本注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    
    //注册通知
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    //如果使用地理围栏功能，需要注册地理围栏代理
    [JPUSHService registerLbsGeofenceDelegate:self withLaunchOptions:launchOptions];
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:jpushAppKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    //APP角标设置为0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    if([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0){//8.0以后使用这种方法来注册推送通知
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    } else {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    }
    
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        }];
        center.delegate = self;
    }
    
    //收到消息(非APNs) 的通知监听(自定义消息)(极光的应用内消息)
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(jPushDidReceiveNotificationMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}
#pragma mark - 收到极光的应用内推送消息处理(非APNs消息)
- (void)jPushDidReceiveNotificationMessage:(NSNotification *)notification {
    //收到的是自定义消息，只有在前端运行的时候才能收到
    NSDictionary * userInfo = [notification userInfo];
    NSLog(@"收到的推送消息:%@",userInfo);
    //    NSString *content = [userInfo valueForKey:@"content"];
    //    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
    //    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    //    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段，key 是自己定义的
}

//获得UUID
- (NSString*)uuid {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
    NSString *result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    return result;
}
//App在前台获取到通知会走该方法
//只有当应用程序位于前台时，该方法才会在委托上调用。如果方法未被执行或处理程序没有及时调用，则通知将不会被提交。
//应用程序可以选择将通知呈现为 声音、徽章、警报、或通知列表中。此决定应基于通知中的信息是否对用户可见。
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    completionHandler(UNNotificationPresentationOptionAlert);
}
#pragma mark - JPUSHRegisterDelegate - 推送注册代理
//iOS10特性 APP在前台获取通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler API_AVAILABLE(ios(10.0)){
    //选择是否提醒用户 Badge Sound Alert三种类型
    completionHandler(UNNotificationPresentationOptionAlert);
    
    NSDictionary *userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]){
        [JPUSHService handleRemoteNotification:userInfo];
    }
}
//iOS10特性 点击通知进入APP
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    completionHandler();//系统要求执行这个方法
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [[NSNotificationCenter defaultCenter] postNotificationName:shengChengFaHuoDanWeiFuKuanSucccessed object:nil];
        [self.alertBgView removeFromSuperview];
        completionHandler();
    }
    
}
//iOS10特性
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}
- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info{
    
}
#pragma mark - JPUSHGeofenceDelegate - 推送地理围栏代理
//进入地理围栏区域
- (void)jpushGeofenceIdentifer:(NSString * _Nonnull)geofenceId didEnterRegion:(NSDictionary * _Nullable)userInfo error:(NSError * _Nullable)error{
    
}

//离开地理围栏区域
- (void)jpushGeofenceIdentifer:(NSString * _Nonnull)geofenceId didExitRegion:(NSDictionary * _Nullable)userInfo error:(NSError * _Nullable)error{
    
}
#pragma mark - 收到本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    NSLog(@"appdfdf收到本地推送(didReceiveLocalNotification:):%@", notification.userInfo);
    
    if (@available(iOS 10.0, *)) {
        
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = [NSString localizedUserNotificationStringForKey:@"Hello77777777" arguments:nil];
        content.body = [NSString localizedUserNotificationStringForKey:[NSString stringWithFormat:@"Agent-%d",arc4random()%100] arguments:nil];
        content.sound = [UNNotificationSound defaultSound];
        UNNotificationRequest *requester = [UNNotificationRequest requestWithIdentifier:@"OXNotification" content:content trigger:nil];
        [center addNotificationRequest:requester withCompletionHandler:^(NSError *_Nullable error) {
            NSLog(@"成功添加推送");
        }];
    }
    
    [self tuisonhg:@"tuisonhg"];
}

-(void)tuisonhg:(NSString *)textstr{
    //加载本地音乐
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"支付宝" withExtension:@"m4a"];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
    if (self.player) {
        [self.player prepareToPlay];
    }
    self.player.volume = 0.5;
    self.player.pan = -1;
    self.player.numberOfLoops = -1;
    self.player.rate = 0.5;
    [self.player play];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){
    NSLog(@"============收到本地推送:%@", response);
}
//当从应用外部通知界面或通知设置界面进入应用时，该方法将回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
}
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段，key 是自己定义的
    NSLog(@"极光iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);//没收到
}


#pragma mark - 收到远程推送
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [JPUSHService handleRemoteNotification:userInfo];
    
    NSLog(@"iOS7及以上系统，收到远程通知:%@", [self logDic:userInfo]);
    
    completionHandler(UIBackgroundFetchResultNewData);
    NSLog(@"获取的信息:%@",userInfo);
     [JPUSHService handleRemoteNotification:userInfo];
    NSDictionary *diccc = @{@"textstr":@""};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:APPDELEGATE_REQUEST_REFRESHLISTDATA object:nil userInfo:diccc];
    if ([[userInfo allKeys] containsObject:@"notice"]) { //有新的通知，请及时查看
        //有新的通知，请及时查看  播放语音
        NSString *sterename = @"youxindetongzhi";
        NSString *filePath = [[NSBundle mainBundle] pathForResource:sterename ofType:@"m4a"];
        NSURL *fileUrl = [NSURL URLWithString:filePath];
        SystemSoundID soundID = 0;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
        AudioServicesAddSystemSoundCompletion(soundID,NULL,NULL,soundCompleteCallBack,NULL);
        AudioServicesPlaySystemSound(soundID);
    } else if ([[userInfo allKeys] containsObject:@"partsReturn"]) {
        //审核状态更改

        [self showAlertText:userInfo[@"aps"][@"alert"]];
    
        
    } else if ([[userInfo allKeys] containsObject:@"cancelReturn"]) {//
        //取消回寄
        [self showAlertText:userInfo[@"aps"][@"alert"]];
    } else if ([[userInfo allKeys] containsObject:@"createPartsOrder"]) {//您有新的未发货单，请及时查看
        NSString *sterename = @"xindeweifahuodan";
        NSString *filePath = [[NSBundle mainBundle] pathForResource:sterename ofType:@"m4a"];
        NSURL *fileUrl = [NSURL URLWithString:filePath];
        SystemSoundID soundID = 0;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
        AudioServicesAddSystemSoundCompletion(soundID,NULL,NULL,soundCompleteCallBack,NULL);
        AudioServicesPlaySystemSound(soundID);

        
    } else if ([[userInfo allKeys] containsObject:@"saveRepairApplyGrants"]) {//有新的补助金申请，请及时查看
        NSString *sterename = @"xindebuzhujinshenqing";
        NSString *filePath = [[NSBundle mainBundle] pathForResource:sterename ofType:@"m4a"];
        NSURL *fileUrl = [NSURL URLWithString:filePath];
        SystemSoundID soundID = 0;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
        AudioServicesAddSystemSoundCompletion(soundID,NULL,NULL,soundCompleteCallBack,NULL);
        AudioServicesPlaySystemSound(soundID);
    }
}
- (void)showAlertText:(NSString*)content {
    
    self.alertBgView = [[UIView alloc] init];
    self.alertBgView.backgroundColor = [UIColor colorWithHexString:@"#999999"];
    self.alertBgView.alpha = 0.9;
    [self.window addSubview:self.alertBgView];
    [self.alertBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.top.offset(0);
    }];
    
    UIView *alertView = [[UIView alloc] init];
    alertView.backgroundColor = UIColor.whiteColor;
    alertView.layer.cornerRadius = 10;
    alertView.layer.masksToBounds = YES;
    [self.alertBgView addSubview:alertView];
    [alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(40);
        make.right.offset(-40);
        make.height.offset(200);
        make.center.equalTo(self.alertBgView);
    }];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    titleLabel.text = @"温馨提示";
    [alertView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.left.offset(20);
        make.right.offset(-20);
        make.height.offset(30);
    }];
    
    UILabel *contentLabel = [[UILabel alloc] init];
    contentLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    contentLabel.font = [UIFont systemFontOfSize:13];
    contentLabel.numberOfLines = 3;
    contentLabel.text = content;
    
    [alertView addSubview:contentLabel];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(20);
        make.left.offset(20);
        make.right.offset(-20);
        make.height.offset(60);
    }];
    
    UIButton *seeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [seeButton setBackgroundImage:[UIImage imageNamed:@"按钮背景"] forState:UIControlStateNormal];
    [seeButton setTitle:@"立即查看" forState:UIControlStateNormal];
    seeButton.layer.cornerRadius = 20;
    seeButton.layer.masksToBounds = YES;
    [seeButton addTarget:self action:@selector(seeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [alertView addSubview:seeButton];
    [seeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(60);
        make.right.offset(-60);
        make.height.offset(40);
        make.bottom.offset(-20);
        
    }];
    
}
- (void)seeButtonClick {
     [[NSNotificationCenter defaultCenter] postNotificationName:shengChengFaHuoDanWeiFuKuanSucccessed object:nil];
    [self.alertBgView removeFromSuperview];
}
void soundCompleteCallBack(SystemSoundID soundID, void *clientData) {
    NSLog(@"声音播放完成");
}

- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

@end
